package com.vv.tools.modules.utils.domain.service.impl;

import com.vv.tools.common.util.FileUtils;
import com.vv.tools.common.util.JsonUtil;
import com.vv.tools.modules.utils.domain.model.CurlRequestBO;
import com.vv.tools.modules.utils.domain.model.ReCaptchResponse;
import com.vv.tools.modules.utils.domain.service.CurlService;
import com.vv.tools.modules.utils.domain.service.ReCaptchaService;

import jakarta.annotation.Resource;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class ReCaptchaServiceImpl implements ReCaptchaService {

    private static final String FILE_PATH = "classpath:config/reCaptcha.json";

    private CurlRequestBO initConfig = null;

    @Resource
    private CurlService curlService;

    @Override
    public boolean verifyToken(String token, String ip) {
        if (StringUtils.isBlank(token)) {
            return false;
        }

        // 获取初始配置
        if (null == initConfig) {
            initConfig = init();
        }

        initConfig.setBatchData(Collections.singletonList(Map.of("response", token, "ip", ip)));
        List<String> curlList = curlService.curl(initConfig);
        if (CollectionUtils.isNotEmpty(curlList)) {
            String resultStr = curlList.get(0);
            ReCaptchResponse response = JsonUtil.toObject(resultStr, ReCaptchResponse.class);
            return null != response && response.getSuccess();
        }
        return false;
    }

    private CurlRequestBO init() {
        String s = FileUtils.read(Objects.requireNonNull(FileUtils.getClassPathFile(FILE_PATH)));
        return JsonUtil.toObject(s, CurlRequestBO.class);
    }

}
